#!/bin/bash
# copy from https://github.com/riobard/dotfiles/blob/master/setup

set -e

if [ ! -e ~/code ]; then
    mkdir -p ~/code
fi

export DOTFILES_DIR=${HOME}/code/dotfiles

linkf() {
    if [ -h ~/."$1" ]; then
        if [ "$(readlink ~/."$1")" !=  "$DOTFILES_DIR"/home_root/"$1" ]; then
            rm -rf ~/."${1}".old
            mv ~/."$1" ~/."$1".old
        else
            return 0
        fi
    elif [ -e ~/."$1" ]; then
        rm -rf ~/."${1}".old
        mv ~/."$1" ~/."${1}".old
    fi

    ln -s "$DOTFILES_DIR"/home_root/"$1"  ~/."$1"
    echo home_root/"$1" linked
    return 0
}

linkd() {
    if [ -h ~/.config/"$1" ]; then
        if [ "$(readlink ~/.config/"$1")" !=  "$DOTFILES_DIR"/config/"$1" ]; then
            rm -rf ~/.config/"$1".old
            mv ~/.config/"$1" ~/.config/"$1".old
        else
            return 0
        fi
    elif [ -e ~/.config/"$1" ]; then
        rm -rf ~/.config/"$1".old
        mv ~/.config/"$1" ~/.config/"$1".old
    fi

    ln -s "$DOTFILES_DIR"/config/"$1"  ~/.config/
    echo config/"$1" linked
    return 0
}

linkroot() {
    for i in "$DOTFILES_DIR"/home_root/*; do
        if [ -e "$i" ]; then
            linkf "$(basename "$i")"
        fi
    done
    echo "files in home_root linked"
    return 0
}

linkconfig() {
    for i in $DOTFILES_DIR/config/*; do
        if [ "$(basename "$i")" == "mimeapps.list" ]; then
            continue;
        fi
        if [ -e "$i" ]; then
            linkd "$(basename "$i")"
        fi
    done
    echo "files in config linked"
    return 0
}

clone() {
    if ! [[ -d "$DOTFILES_DIR" ]]; then
        git clone https://gitee.com/dgeibi/dotfiles.git "$DOTFILES_DIR"
    else
        cd "$DOTFILES_DIR"
        git pull
    fi
    return 0
}

vim-plug() {
    if ! [[ -e  ~/.vim/autoload/plug.vim ]]; then
        curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
    fi
    which vim >/dev/null 2>&1 && vim +PlugInstall +qa
    return 0
}

installnvm() {
    if ! [[ -e ~/.nvm ]]; then
        git clone https://github.com/creationix/nvm.git ~/.nvm && cd ~/.nvm && git checkout "$(git describe --abbrev=0 --tags)"
        . "$HOME"/.nvm/nvm.sh
        nvm install "$(nvm ls-remote | tail -1 | tr -d ' ')"
        cd -
    fi
    return 0
}

installgitcompletion() {
    if [ ! -f ~/.git-completion.bash ]; then
        curl -L https://git.io/vfhol > ~/.git-completion.bash
    fi
    return 0
}

installGitPrompt() {
    if [ ! -f ~/.git-prompt.sh ]; then
        curl -L https://git.io/v5oou > ~/.git-prompt.sh
    fi
    return 0
}

installmimeappslist() {
    if [ ! -f ~/.config/mimeapps.list ]; then
        install -Dm644 "$DOTFILES_DIR"/config/mimeapps.list ~/.config/mimeapps.list
    fi
    return 0
}

clone
linkroot
linkconfig
# installmimeappslist
vim-plug
# installnvm
installgitcompletion
installGitPrompt